{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def load_mnist(file_path):\n",
    "    '''\n",
    "    读取文件夹mnist下的42000张图片，图片为灰度图, 大小为28*28\n",
    "    '''\n",
    "    data = np.empty((42000, 1, 28, 28), dtype=\"float32\")  # 训练数据初始化\n",
    "    label = np.empty((42000,), dtype=\"uint8\")  # 训练label初始化\n",
    "\n",
    "    imgs = os.listdir(file_path)\n",
    "    num = len(imgs)\n",
    "\n",
    "    for i in range(num):\n",
    "        img = Image.open(file_path + imgs[i])\n",
    "        img_arrary = np.asarray(img, dtype=\"float32\")\n",
    "        data[i, :, :, :] = img_arrary\n",
    "        label[i] = int(imgs[i].split('.')[0])  # 提取命名首字母作为label\n",
    "\n",
    "    return data, label\n",
    "\n",
    "data, label = load_mnist('./mnist/')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
